package com.xiong.fan.factory;

import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * spring循环依赖
 *
 */
public class BeanFactory {
    private  static Map<String,Object> map = new HashMap<>();

    public static void main( String[] args ){
        System.out.println( "Hello World!" );
//        // 假装扫描出来的对象
//        Class[] classes = {A.class, B.class};
//        // 假装项目初始化实例化所有bean
//        for (Class aClass : classes) {
//            getBean(aClass);
//        }


    }




    @lombok.SneakyThrows
    private static <T> T getBean(Class<T> beanClass){
        String beanName=beanClass.getSimpleName().toLowerCase();
        if(map.containsKey(beanName)){
            return (T) map.get(beanClass);
        }

       Object object = beanClass.getDeclaredConstructor().newInstance();
        map.put(beanName,object);

        Field[] fields =object.getClass().getFields();
        for(Field field :fields){
            field.setAccessible(true);
            if(field.isAnnotationPresent(Autowired.class)){
               Class<?> type = field.getType();
               String fieldName=type.getSimpleName().toLowerCase();
                field.set(object, map.containsKey(fieldName)? map.get(fieldName):getBean(type));
            }
        }
        return (T) object;
    }

    /**
     * 给定一个数组，给定一个数字。返回数组中可以相加得到指定数字的两个索引。
     *
     * 比如：给定nums = [2, 7, 11, 15], target = 9
     * 那么要返回 [0, 1]，因为2 + 7 = 9
     */

    public int[] twoSum(int[] nums,int target) throws IllegalAccessException {
        Map<Integer,Integer> map =new HashMap();

        for(int i=0;i<nums.length;i++){
            int compent =target-nums[i];
            if(map.containsKey(compent)){
                return new int[]{i, (int) map.get(compent)};
            }
            map.put(nums[i],i);
        }
        throw new IllegalAccessException("no two solution");




    }


}




